<?php
/**
 * Created by PhpStorm.
 * User: 张福来
 * Date: 2018/10/27
 * Time: 11:45
 */
namespace app\api\controller;

use think\Db;
use app\api\model\Cash as CashModel;
use app\api\validate\Apivalidate;
use app\api\model\User as UserModel;
use app\api\model\Carinfor as CarModel;
use app\api\model\Device as DeviceModel;
use think\Request;

class Cash extends Base{
    /*
    * Notes:商户查询/商户列表
    * Create Date: 2018/10/28
    * Create Time: 15:42
    * Create by :张福来
    * $pageNum : 页数
    * $listNum : 查询条数
    * $start_time : 查询开始时间
    * $end_time : 查询结束时间
    */
    public function selectCash(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"CashValidate.selectCash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $pageNum = $postData["pagenum"];

        if(empty($postData["listNum"])){
            $listNum = 10;
        }else{
            $listNum = $postData["listNum"];
        }
        if(!empty($postData["a_id"])){
            $w["c.a_id"] = $postData["a_id"];
        }
        $w["c.status"] = array('NEQ',9);
        if(!empty($postData["name"])){
            $w['c.name'] = array('LIKE','%'.trim($postData["name"]).'%');
        }
        if(!empty($postData["status"])){
            $w["c.status"] = $postData["status"];
        }
        if(!empty($postData["start_time"]) && !empty($postData["end_time"])){
            $start_time = $postData["start_time"] ." 00:00:00";
            $end_time = $postData["end_time"] . " 23:59:59";
            $w['c.ctime'] = array(array('EGT',strtotime($start_time)),array('ELT',strtotime($end_time)),'and');
        }
        $result = $cash->selectCash($pageNum,$listNum,$w);

        if (!empty($result["list"])){
            return apiResponse(200,"查询成功",$result);
        }else{
            return apiResponse(200,"数据为空",$result);
        }
    }
    /*
    * Notes: 附近的商户列表
    * Create Date: 2018/10/5
    * Create Time: 上午10:41
    * Create by :张福来
    * param :
    */
    public function nearCash(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"CashValidate.nearCash");
        $lat = $postData["lat"];
        $lnt = $postData["lon"];
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $pageNum = $postData["pagenum"];
        if(empty($postData["listNum"])){
            $listNum = 10;
        }else{
            $listNum = $postData["listNum"];
        }
        $w["c.status"] = array('NEQ',9);
        $result = $cash->nearCash($pageNum,$listNum,$w,$lat,$lnt);
        $list = $result["list"];
        $attestation = $result["attestation"];
        $count = count($list);
        $returnarray["list"] = $result["list"];
        $count3 = count($attestation);
        for($i = 0; $i<$count;$i++){
            for($j = 0;$j<$count3;$j++){
                if($list[$i]["a_id"] == $attestation[$j]["a_id"]){
                    if(!empty($attestation[$j]["att_name"]) && !empty($attestation[$j]["pic_path"])){
                        $arrayname = explode(',',$attestation[$j]["att_name"]);
                        $arraypic =  explode(',',$attestation[$j]["pic_path"]);
                        $count2 = count($arrayname);
                        $array = array();
                        for($x = 0; $x<$count2;$x++){
                            array_push($array,["name"=>$arrayname[$x],"pic"=>$arraypic[$x]]);
                        }
                    }else{
                        $array = [];
                    }
                    $returnarray["list"][$i]["attestation"] = $array;
                    array_splice($attestation,$j,1);
                    $j--;
                    $count3 = count($attestation);
                }
            }

        }
        $returnarray["total"] =  $result["total"];
        if(!empty($result["list"])){
            return  apiResponse(200,"查询成功",$returnarray);
        }else{
            return  apiResponse(200,"数据为空",$returnarray);
        }

    }
    /*
    * Notes: 添加商户
    * Create Date: 2018/10/27
    * Create Time: 17:28
    * Create by :张福来
    * Param :
    *  account：商户登录账号
    *  name：商户名称
    *  contactnum：联系电话
    *  legal_person：法人姓名
    *  id_number：法人身份证号
    *  password：登录密码
    *  ctime：创建时间
    *  wallet：账户余额
    *  score：评分
    *  support_reserve：是否支持预约到店 0 不支持 1 支持
    *  get_car：是否支持上门取车 0 不支持 1 支持
    *  break_scale：退还上门服务的比例 单位%
    *  off_order_time：允许取消订单的时间，分钟
    *  hour_free：工时费
    *  cover_oldprice：服务费原价
    *  cover_nowprice：服务费现价
    *  detailed_address：详细地址
    *  service_radius：服务半径 单位km
    *  type：商户类型 1维修商户 2洗车商户
    *  添加成功返回 code:200
    *  添加失败返回 code:201
    */
    public function addCash(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"CashValidate.addCash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        if(empty($postData["account"])){
            return apiResponse(201,"商户登录账号不能为空","");
        }else{
            $sql = Db::name('cash')
                ->where(array("account" =>$postData["account"],'status'=>array('neq','9')))
                ->column("account");
            if(!empty($sql)){
               return apiResponse(201,"商户已注册","");
            }
        }
        $password = substr($postData["account"],-6);
        $postData["password"] = md5($password);
        $postData["ctime"]=time();
        $postData["utime"]=time();
        $reslt = $cash ->addCash($postData);
        if($reslt){
            return apiResponse(200,"商户注册成功",["a_id"=>$reslt]);
        }else{
            return apiResponse(201,"商户注册失败","");
        }
    }
      /*
      * Notes: 修改商户
      * Create Date: 2018/10/27
      * Create Time: 17:28
      * Create by :张福来
      * Param :
      *  a_id：商户id
      *  account：商户登录账号
      *  name：商户名称
      *  contactnum：联系电话
      *  legal_person：法人姓名
      *  id_number：法人身份证号
      *  password：登录密码
      *  utime：修改时间
      *  添加成功返回 code:200
      *  添加失败返回 code:201
      */
    public function editCash(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"CashValidate.editCash");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $postData["utime"]=time();
        $reslt = $cash ->editCash($postData);
        if($reslt){
            return apiResponse(200,"商户修改成功","");
        }else{
            return apiResponse(201,"商户修改失败","");
        }
    }

    public function editPassword(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $check = $this->validate($postData,"CashValidate.editPassword");
        if($check !== true){
            return apiResponse(201,$check,"");
        }
        $w['a_id'] = $postData['a_id'];
        $hascash = $cash -> findCash( $w );
        if (!empty($hascash) && $hascash['password'] == md5($postData['password'])) {
            $w["utime"]=time();
            $w["password"]=md5($postData['new_password']);
            $reslt = $cash ->editCash($w);
        }else{
            return apiResponse("201","商户不存在或原密码不正确！");
        }
        if($reslt){
            return apiResponse(200,"密码修改成功");
        }else{
            return apiResponse(201,"密码修改失败");
        }
    }
    /*
    * Notes:删除商户
    * Create Date: 2018/10/28
    * Create Time: 14:01
    * Create by :张福来
    * $a_id : 商户id
    */
    public function deletCash(Request $request){
        $cash = new CashModel;
        $postData = $request->post();
        $a_id = $postData["a_id"];
        $reslt = $cash->deleteCash($a_id);
        if($reslt){
            return apiResponse(200,"商户删除成功","");
        }else{
            return apiResponse(201,"商户删除失败","");
        }
    }

    /**
     * Notes: 商户登錄
     * Create Date: 2018/10/2
     * Create Time: 15:34
     * Create by :lijie
     */
    public function login(Request $request){

        $cash = new CashModel();

        // 获取数据并验证
        $param = $request->post();
        $resVali = $this->validate($param,"CashValidate.login");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }

        $account    = $param['account'];
        $password   = $param['password'];

        // 用户是否存在
        $w['account']   = $account;
        $w['status']    = 0;
        $cashInfo = $cash->findCash($w);
        if($cashInfo){
            // 密码正确否
            if($cashInfo['password'] == md5($password)){
                $save['last_login_time']    = time();
                $save['last_login_ip']      = $_SERVER['REMOTE_ADDR'];
                $save['a_id']               = $cashInfo['a_id'];
                $res = $cash->editCash($save);
                if($res){
                    return apiResponse(200,'登录成功',$cashInfo['a_id']);
                }else {
                    return apiResponse(201,'登录失败','');
                }
            }else {
                return apiResponse(201,'密码不正确','');
            }
        }else {
            $cashChild = Db::name('cash_child')->where($w)->field("a_id,password")->find();
            if($cashChild){
                // 判断密码是否正确
                if($cashChild['password'] == md5($password)){
                    return apiResponse(200,'登录成功',$cashChild['a_id']);
                }else {
                    return apiResponse(201,'密码不正确','');
                }
            }else {
                return apiResponse(201,'该账号不存在','');
            }
        }
    }

    /**
     * Notes: 判断手机号是否绑定用户
     * Create Date: 2018/10/2
     * Create Time: 15:34
     * Create by :lijie
     */
    public function bindUser(Request $request){
        $user = new UserModel();

        // 验证
        $param = $request->post();
        $resVali = $this->validate($param,"CashValidate.bindUser");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }
        $phone = $param['phone'];

        $userInfo = $user->checkUserLogin(['phone'=>$phone,'status'=>0]);
        if($userInfo){
            return apiResponse(200,'用户存在',1);
        }else {
            return apiResponse(201,'用户不存在',2);
        }
    }

    /**
     * Notes: 商户发送obd给用户
     * Create Date: 2018/10/2
     * Create Time: 15:34
     * Create by :lijie
     */
    public function sendObdToUser(Request $request){

        $device = new DeviceModel();
        $user = new UserModel();

        // 验证数据
        $param    = $request->post();
        $resVali  = $this->validate($param,"CashValidate.sendObdToUser");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }

        // 根据手机号判断该用户是否存在,存在输入车辆信息，不存在输入用户信息和车辆信息
        $userInfo = $user->checkUserLogin(['phone'=>$param['phone'],'status'=>0]);
        $u_id = $userInfo['u_id'];
        $head_pic = $userInfo['head_pic'];
        if(!empty($head_pic)){
            $w_device['path']       = $head_pic;            // 头像图片路径
        }
        if(!$userInfo){
           if(empty(input('post.name'))){
                return apiResponse(201,'name参数错误','');
            }if(empty(input('post.phone'))){
                return apiResponse(201,'phone参数错误','');
            }

            $save_user['name']          = $param['name'];
            $save_user['phone']         = $param['phone'];
            $save_user['ctime']         = time();
            $save_user['status']        = 0;

            $res_user = Db::name('user')->insertGetId($save_user);
            $u_id = $res_user;
        }

        // 根据车牌号判断，车辆是否添加过
        $carHas = Db::name('carinfor')->where(['licenseplate'=>$param['licenseplate'],'status'=>0])->field('c_id')->find();
        if($carHas){
            return apiResponse(201,'该车已经绑定obd设备了','');
        }

        // 添加车辆信息
        $save_car['u_id'] = $u_id;
        $save_car['o_id'] = $param['id'];
        $save_car['a_id'] = $param['a_id'];
        $save_car['b_id'] = $param['b_id'];
        $save_car['t_id'] = $param['t_id'];
        $save_car['m_id'] = $param['m_id'];
        $save_car['b_name'] = $param['b_name'];
        $save_car['t_name'] = $param['t_name'];
        $save_car['m_name'] = $param['m_name'];
        $save_car['licenseplate'] = $param['licenseplate'];
        $save_car['ctime'] = time();
        $save_car['status'] = 0;
        $res_car = Db::name('carinfor')->insertGetId($save_car);

        // 更新obd设备信息
        $bindTime = date("Y-m-d H:i:s",time());
        // 条件
        $w_device['car_id']     = $res_car;             // 车辆id
        $w_device['bind_time']  = $bindTime;            // 绑定时间
        $w_device['modify_time']= $bindTime;            // 更新时间
        $w_device['issued_time']= $bindTime;            // 下发时间
        $w_device['member_id']  = $u_id;                // 会员id(即用户id)
        $w_device['path']       = $head_pic;            // 头像图片路径
        $w_device['status']     = 2;
        $con['id']               = $param['id'];

        $res = $device->updateDevice($w_device,$con);
        if($res && $res_car){
            return apiResponse(200,'绑定成功',$res);
        }else {
            return apiResponse(201,'绑定失败',$res);
        }
    }

    /**
     * Notes:  商户添加认证
     * Create Date: 2018/10/30
     * Create by :lijie
     */
    public function addAttestation(Request $request)
    {
        $cash = new CashModel();
        // 验证
        $param = $request->post();
        $resVali = $this->validate($param,"CashValidate.addAttestation");
        if($resVali !== true){
            return apiResponse(201,$resVali,'');
        }
        //
        $where['status']    = 0;
        $where['a_id']      = $param['a_id'];
        $res = $cash->editCashAttest($param,$where);
        if($res){
            return apiResponse(200,'编辑成功',$res);
        }else {
            return apiResponse(201,"编辑失败",$res);
        }
    }

    /**
     * Notes:  商户更绑手机号
     * Create Date: 2018/10/9
     * Create by :lijie
     */
    public function bindPhone(Request $request)
    {
        $cash = new CashModel();
        $param = $request->post();
        //
        if (!empty($param['phone']) && empty($param['code'])){      // 验证码空
            $res = $this->sendSms($param['phone'],2,"changephone");
            if ($res){
                return apiResponse(200,'短信发送成功',$res);
            }else {
                return apiResponse(201,"短信发送失败",$res);
            }
        }
        if (empty($param['phone']) && !empty($param['code'])){      // 手机号空
            return apiResponse(201,'手机号不能为空','');
        }
        if (empty($param['phone']) && empty($param['code'])){       // 全空
            return apiResponse(201,'参数不全','');
        }
        if (!empty($param['phone']) && !empty($param['code'])){     // 全
            // 判断验证码
            if ($param['code'] != cache("phonechangephone".$param['phone'])){
                return apiResponse(201,'验证码不正确或过期','');
            }
            //
            $where['a_id']  = $param['a_id'];
            $param['account'] = $param['phone'];
            unset($param['a_id']);
            $res = $cash->isUpdate(true)->allowField(true)->save($param,$where);
            if ($res){
                cache("phonechangephone".$param['phone'],NULL); //绑定成功后 清除缓存
                return apiResponse(200,'绑定成功','');
            }else {
                return apiResponse(201,'绑定失败','');
            }
        }
    }


}
